#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users

import logging

import feedreader

from model.twitterstatus import clearAll as clearAllTwitterStatuses
from model.lasttwitterid import clearAll as clearAllLastIds

import oauthtwitter


from ui import links
from ui import startpage
                                   

def _isGoodUser(requestHandler):
    user = users.get_current_user()
    if user:                                                    
        logging.info("Good user")
        return users.is_current_user_admin()
    else:                      
        logging.info("Bad user or no user, logging in...")
        requestHandler.response.redirect(users.create_login_url(requestHandler.request.url))
        return False

class MainHandler(webapp.RequestHandler):
    
  def get(self):
      user = self.request.get('user')
      filter = self.request.get('search')
      
      if len(user) > 1:
          if len(filter) < 1:
              filter = None
          
          ui = links.LinksUI(user, filter, request=self.request)
      else:
          client = oauthtwitter.OAuthClient('twitter', self)
          if client.get_cookie():
              info = client.get('/account/verify_credentials')
              screen_name = info['screen_name']
              ui = startpage.StartPage(loggedIn = True, username = screen_name)
          else:
              ui = startpage.StartPage()
      
      ui.render(self.response.out)
    

class ServiceHandler(webapp.RequestHandler):
    def get(self):
        if not _isGoodUser(self):
            self.response.out.write("You're definitely a user, but you're not a good user. So -- tough luck mate")                                       
            return
        
        if 'clearStatuses' == self.request.get('action'):
            clearAllLastIds()
            clearAllTwitterStatuses()
        else:                     
            logging.info("You know..")
            self.response.out.write("You're logged in into the service area. You know what you should do.")


def main():
    logging.getLogger().setLevel(logging.DEBUG)
    webapp.template.register_template_library('customfilters')
    application = webapp.WSGIApplication([('/', MainHandler), 
                                          ('/service', ServiceHandler), 
                                          ('/oauth/(.*)/(.*)', oauthtwitter.OAuthHandler),
                                          ('/twitter_callback', oauthtwitter.CallbackHandler)
                                          ], debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
